/*
 * WelcomeFrame.java
 */

package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import exceptions.UPException;

import model.ListManager;
import model.Role;
import model.User;

import gui.GUIUtil;

/**
 * JFrame for the WelcomeFrame GUI.  Accepts user email address and
 * determines login actions.
 * 
 * @author Sean Brown
 * @version 1.0
 */
@SuppressWarnings("serial")
public class WelcomeFrame extends JFrame {

	/**
	 * Default window size.
	 */
	private static final Dimension WINDOW_SIZE = new Dimension(400, 370);

	/**
	 * The text field that the user can fill out their email address in.
	 */
	private final JTextField my_email_field;
	
	/**
	 * ListManager to use for accessing and managing data.
	 */
	private final ListManager my_lm;
	
	/**
	 * Boolean to determine if the import of data was successful.
	 */
	private boolean import_successful;
	
	/**
	 * CalendarFrame to show to Staff Members when they login.
	 */
	private CalendarFrame my_cal_frame;
	
	/**
	 * ManagerFrame to show Park Managers when they login.
	 */
	private ManagerFrame my_man_frame;
	
	/**
	 * VolunteerFrame to show Volunteers when they login.
	 */
	private VolunteerFrame my_vol_frame;

	/**
	 * Constructs a welcome frame for the UrbanParks program.
	 */
	public WelcomeFrame() {
		super("Urban Parks: Welcome");
		my_lm = new ListManager();
		try {
			my_lm.importData();
			import_successful = true;
		} catch (final UPException upe) {
			GUIUtil.errorMessage(this, upe.getMessage());
			setVisible(true);
		}
		my_email_field = new JTextField();
	}

	/**
	 * Sets up all panels, preferences, and shows the frame
	 * on screen.
	 */
	public void start() {
		if (import_successful) {
			setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			UIManager.put("Panel.background", Color.WHITE);
	        
			//Input panel
			final JPanel main_layout = new JPanel(new BorderLayout());
			main_layout.add(logoPanel(), BorderLayout.NORTH);
			main_layout.add(submitPanel(), BorderLayout.CENTER);
	    
			add(main_layout);
			setPreferredSize(WINDOW_SIZE);
			pack();
			setLocationRelativeTo(getRootPane());
			setVisible(true);
		}
	}

	/**
	 * Returns the Panel containing the Urban Parks logo.
	 * 
	 * @return JPanel the logo panel
	 */
	private JPanel logoPanel() {
		ImageIcon icon_logo;
		Image logo_image = Toolkit.getDefaultToolkit().getImage
				(getClass().getClassLoader().getResource("images/urbanparks_sml.jpg"));
		icon_logo = new ImageIcon(logo_image);
        JLabel logo = new JLabel(icon_logo);
		final JPanel logo_panel = new JPanel(new BorderLayout());
		logo_panel.add(logo, BorderLayout.CENTER);
		return logo_panel;
	}
  
	/**
	 * Returns a JPanel containing the text field and button for
	 * logging in.
	 * 
	 * @return JPanel the panel with email text field and submit button.
	 */
	private JPanel submitPanel() {
		final JPanel submit_panel = new JPanel(new BorderLayout());
		submit_panel.setBorder(BorderFactory.createTitledBorder("Enter your email address:"));
		
		//Create ActionListener
		final ActionListener listener = new SubmitButtonAL();
		
		//Create JButton
		final JPanel submit_button_pnl = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		final JButton submit_button = new JButton("Submit");
		submit_button.setSize(getMinimumSize());
		submit_button.addActionListener(listener);
		submit_button_pnl.add(submit_button);
		
		//Setup Text Field
		final JPanel txt_field_pnl = new JPanel(new BorderLayout());
		my_email_field.addActionListener(listener);
		txt_field_pnl.add(my_email_field);
		
		//Add all to panel and return
	    submit_panel.add(txt_field_pnl, BorderLayout.CENTER);
	    submit_panel.add(submit_button_pnl, BorderLayout.SOUTH);
	    return submit_panel;
	}
	
	/**
	 * Exit procedure for the program.  Prompts the user if they want
	 * to save the changes they have made before exiting.
	 */
	public void exitProcedure(final JFrame the_caller) {
		final int option = JOptionPane.showConfirmDialog(new JFrame(),
                "Do you wish to save changes before exiting the program?", 
                "Confirm Save",
                JOptionPane.YES_NO_CANCEL_OPTION);
		if (option == JOptionPane.YES_OPTION) {
			try {
				my_lm.exportData();
				the_caller.dispose();
				dispose();
			} catch (final UPException e) {
				GUIUtil.errorMessage(new JFrame(), e.getMessage());
			}
		} else if (option == JOptionPane.NO_OPTION){
			the_caller.dispose();
			dispose();
		} else if (option == JOptionPane.CANCEL_OPTION) {
			//do nothing.
		}
	}
	
	/**
	 * Determines the type of user passed and opens the corresponding
	 * Frame.
	 * 
	 * @param the_user The current user.
	 */
	private void login(final User the_user) {
		my_lm.switchUser(the_user);
		my_email_field.setText("");
		if (the_user.getRole().equals(Role.VOLUNTEER)) {
			if (the_user.isBlackballed()) {
				GUIUtil.errorMessage(this, "Please contact Urban Parks staff to sign up for" + 
						" new jobs.");
			} else {
				my_vol_frame = new VolunteerFrame(this, my_lm);
				my_vol_frame.start();
				this.setVisible(false);
			}
		} else if (the_user.getRole().equals(Role.PARKMANAGER)) {
			my_man_frame = new ManagerFrame(this, my_lm);
			my_man_frame.start();
			this.setVisible(false);
		} else if(the_user.getRole().equals(Role.STAFFMEMBER)) {
			my_cal_frame = new CalendarFrame(this, my_lm);
			my_cal_frame.start();
			this.setVisible(false);
		} else {
			GUIUtil.errorMessage(this, "The user type associated with your email address is invalid." +
					"\nPlease contact Urban Parks for further assistance.");
		}
	}
	
	/**
	 * ActionListener for the WelcomeFrame class.  Logs in for the
	 * user if the email is valid.  Otherwise displays an error.
	 */
	public class SubmitButtonAL implements ActionListener {

		public void actionPerformed(final ActionEvent the_event) {
			if (!my_email_field.getText().isEmpty()) {
				final String email = my_email_field.getText();
				try {
					login(my_lm.findUser(email.toLowerCase().hashCode()));
				} catch (final UPException upe) {
					GUIUtil.errorMessage(WelcomeFrame.this, "The email address \"" + email + 
							"\" is not registered.\nPlease contact Urban" +
							" Parks for further assistance.");
					my_email_field.setText("");
				}
			} else {
				GUIUtil.errorMessage(WelcomeFrame.this, "Please enter a valid email address.");
			}
		}
	}
}